<template>
  <div class="track-parking-container">
    <n-grid :cols="24" :x-gap="12" style="height: calc(100vh - 150px)">
      <!-- 左侧组织机构树 -->
      <n-gi :span="6">
        <OrgTree
          ref="orgTreeRef"
          @set="handleOrgSelect"
          @reload="handleOrgReload"
          @loaded="handleOrgTreeLoaded"
        />
      </n-gi>

      <!-- 右侧股道占位板卡片列表 -->
      <n-gi :span="18">
        <n-card :title="cardTitle" style="height: 100%">
          <!-- 搜索区域 -->
          <div class="search-area">
            <n-input
              v-model:value="searchTrackName"
              placeholder="请输入股道名称进行搜索"
              clearable
              style="width: 300px; margin-bottom: 16px"
              @update:value="handleSearch"
            >
              <template #prefix>
                <n-icon><SearchOutlined /></n-icon>
              </template>
            </n-input>
          </div>

          <!-- 卡片列表 -->
          <n-grid
            v-if="filteredTrackList.length > 0"
            :cols="2"
            :x-gap="12"
            :y-gap="12"
            responsive="screen"
          >
            <n-gi v-for="track in filteredTrackList" :key="track.trackId">
              <n-card :title="track.trackName" size="small" hoverable class="track-card">
                <template #header-extra>
                  <n-tag :type="getTrackTypeTagType(track.trackType)">
                    {{ track.trackTypeName }}
                  </n-tag>
                </template>

                <n-descriptions label-placement="left" size="small" :column="1">
                  <n-descriptions-item label="股道长度">
                    {{ track.trackLength }}米
                  </n-descriptions-item>
                  <n-descriptions-item label="创建时间">
                    {{ track.createTime }}
                  </n-descriptions-item>
                  <n-descriptions-item label="更新时间">
                    {{ track.updateTime }}
                  </n-descriptions-item>
                </n-descriptions>

                <n-divider title-placement="left" style="margin: 12px 0"> 停车信息 </n-divider>

                <div v-if="track.parkingList && track.parkingList.length > 0">
                  <n-scrollbar style="max-height: 150px">
                    <n-list>
                      <n-list-item
                        v-for="(parking, index) in track.parkingList"
                        :key="index"
                        class="parking-item"
                      >
                        <n-thing>
                          <template #header> 停车位 {{ index + 1 }} </template>
                          <template #description>
                            <n-ellipsis v-if="parking.description">
                              描述: {{ parking.description }}
                            </n-ellipsis>
                          </template>
                          <div class="parking-details">
                            <n-text depth="3">
                              状态:
                              <n-tag
                                :type="parking.status === 'occupied' ? 'error' : 'success'"
                                size="small"
                              >
                                {{ parking.status === 'occupied' ? '占用' : '空闲' }}
                              </n-tag>
                            </n-text>
                          </div>
                        </n-thing>
                      </n-list-item>
                    </n-list>
                  </n-scrollbar>
                </div>
                <div v-else class="no-parking">
                  <n-empty description="暂无停车信息" size="small" />
                </div>
              </n-card>
            </n-gi>
          </n-grid>

          <!-- 空状态 -->
          <n-empty
            v-else
            description="暂无股道占位板"
            style="
              height: calc(100% - 100px);
              display: flex;
              align-items: center;
              justify-content: center;
            "
          />
        </n-card>
      </n-gi>
    </n-grid>
  </div>
</template>

<script setup lang="ts">
  import { ref, computed, watch } from 'vue';
  import { useMessage } from 'naive-ui';
  import { SearchOutlined } from '@vicons/antd';
  import OrgTree from '@/views/businessPages/comp/org/orgTree.vue';
  import { getTrackParkingList } from '@/api/business/stationManager/trackTable';

  // 类型定义
  interface ParkingInfo {
    description?: string;
    status: 'occupied' | 'free';
    [key: string]: any;
  }

  interface TrackParkingInfo {
    coordinatesList: Array<{
      coordinatesId: string;
      latitude: number;
      longitude: number;
      sort: number;
      trackId: string;
    }>;
    createId: string;
    createName: string;
    createTime: string;
    orgId: string;
    parkingList: ParkingInfo[];
    stationId: string;
    trackId: string;
    trackLength: number;
    trackName: string;
    trackType: string;
    updateId: string;
    updateName: string;
    updateTime: string;
    trackTypeName: string;
  }

  const message = useMessage();
  const orgTreeRef = ref();
  const trackParkingTableRef = ref();

  // 当前选中的组织ID
  const selectedOrgId = ref<string>('');
  const selectedOrgName = ref<string>('');

  // 股道占位板列表
  const trackParkingList = ref<TrackParkingInfo[]>([]);

  // 搜索关键词
  const searchTrackName = ref<string>('');

  // 加载状态
  const loading = ref<boolean>(false);

  // 添加一个 ref 来标识组织树是否已加载
  const orgTreeLoaded = ref(false);

  // 计算card标题
  const cardTitle = computed(() => {
    return selectedOrgName.value ? `${selectedOrgName.value} - 股道占位板` : '股道占位板';
  });

  // 过滤后的股道列表
  const filteredTrackList = computed(() => {
    if (!searchTrackName.value) {
      return trackParkingList.value;
    }

    return trackParkingList.value.filter((track) =>
      track.trackName.toLowerCase().includes(searchTrackName.value.toLowerCase())
    );
  });

  // 获取股道类型标签类型
  function getTrackTypeTagType(trackType: string) {
    const typeMap: Record<string, any> = {
      '1': 'info', // 到发线
      '2': 'warning', // 调车线
      '3': 'success', // 货物线
      '4': 'default', // 其他
    };
    return typeMap[trackType] || 'default';
  }

  // 处理搜索
  function handleSearch() {
    // 搜索逻辑已在 computed 中实现
  }

  // 获取股道占位板
  async function fetchTrackParkingList(orgId: string) {
    if (!orgId) return;

    try {
      loading.value = true;
      const params = { orgId };
      const result = await getTrackParkingList(params);
      trackParkingList.value = result || [];
    } catch (error) {
      message.error('获取股道占位板失败: ' + (error.message || '未知错误'));
      trackParkingList.value = [];
    } finally {
      loading.value = false;
    }
  }

  // 处理组织树加载完成事件
  function handleOrgTreeLoaded() {
    orgTreeLoaded.value = true;
    // 获取根节点并初始化表格
    initializeTableWithRootNode();
  }

  // 处理组织机构选择
  function handleOrgSelect(id: string, name: string) {
    selectedOrgId.value = id;
    selectedOrgName.value = name;
    // 获取股道占位板
    fetchTrackParkingList(id);
  }

  // 处理组织树重新加载
  function handleOrgReload() {
    console.log('组织树重新加载完成');
  }

  // 初始化表格数据
  async function initializeTableWithRootNode() {
    if (orgTreeRef.value && typeof orgTreeRef.value.getRootNodeId === 'function') {
      const rootId = orgTreeRef.value.getRootNodeId();
      if (rootId) {
        selectedOrgId.value = rootId;
        fetchTrackParkingList(rootId);
      }
    }
  }

  // 监听组织ID变化
  watch(selectedOrgId, (newOrgId) => {
    if (newOrgId) {
      fetchTrackParkingList(newOrgId);
    }
  });
</script>

<style scoped>
  .track-parking-container {
    padding: 16px;
    height: 100%;
    box-sizing: border-box;
  }

  :deep(.n-card) {
    height: 100%;
  }

  .search-area {
    margin-bottom: 16px;
  }

  .track-card {
    height: 100%;
    display: flex;
    flex-direction: column;
  }

  .track-card :deep(.n-card__content) {
    flex: 1;
    overflow: hidden;
    display: flex;
    flex-direction: column;
  }

  .parking-item {
    padding: 8px 0;
  }

  .parking-details {
    margin-top: 4px;
  }

  .no-parking {
    text-align: center;
    padding: 20px 0;
  }
</style>
